package org.tinygroup.tinytest;

import org.springframework.context.ApplicationContext;
import org.springframework.core.style.ToStringCreator;
import org.springframework.test.context.CacheAwareContextLoaderDelegate;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.util.Assert;

public class TinyMergedContextConfiguration extends MergedContextConfiguration {

	private MergedContextConfiguration mergedContextConfiguration;

	private MergedContextConfiguration parentConfiguration;

	private final CacheAwareContextLoaderDelegate contextLoaderDelegate;

	public TinyMergedContextConfiguration(ContextLoader contextLoader,
			CacheAwareContextLoaderDelegate contextLoaderDelegate,
			MergedContextConfiguration mergedContextConfiguration,
			MergedContextConfiguration parentConfiguration) {
		super(mergedContextConfiguration.getTestClass(),
				mergedContextConfiguration.getLocations(),
				mergedContextConfiguration.getClasses(),
				mergedContextConfiguration.getActiveProfiles(), contextLoader);
		this.mergedContextConfiguration = mergedContextConfiguration;
		this.contextLoaderDelegate = contextLoaderDelegate;
		this.parentConfiguration = parentConfiguration;
	}

	public ApplicationContext getParentApplicationContext() {
		MergedContextConfiguration parent = mergedContextConfiguration
				.getParent();
		Assert.state(
				this.contextLoaderDelegate != null,
				"Cannot retrieve a parent application context without access to the CacheAwareContextLoaderDelegate");
		if (parent == null) {
			return this.contextLoaderDelegate.loadContext(parentConfiguration);
		}
		ApplicationContext applicationContext = this.contextLoaderDelegate
				.loadContext(parent);
		if (applicationContext == null) {
			applicationContext = this.contextLoaderDelegate
					.loadContext(parentConfiguration);
		}
		return applicationContext;
	}

	@Override
	public String toString() {
		return new ToStringCreator(this)
				.append("orignalMergedContextConfiguration",
						this.mergedContextConfiguration)
				.append("parentMergedContextConfiguration",
						this.parentConfiguration).toString();
	}

}
